/*
Dependencies: messagedisplayer prototype scriptaculous mainApp sapp
*/
var loading = $('loading');
loading.style.display = 'none';

var middle_col = $('middle_col');
var newest = $('newest_col');

//var ads = $('banner_ads');
//ads.style.display = 'none';

var box_bottom_height = 61;
var iframe = $('blog_page');

checkIframeHeight();
window.setInterval("checkIframeHeight();", 1000);

//window.setTimeout(displayAds, 5000);
function displayAds() {
	newest.style.display = 'none';
	Effect.Appear(ads);
	window.setTimeout(closeAds, 20000);// display ads for 20s
}

function closeAds() {
	setTimeout("newest.style.display = ''", 600);
	Effect.Fade(ads, {duration:0.5});
}
var rating=false;
var fav=false;
function dorate(type) {
	Effect.Appear(loading);
	new Ajax.Request(base_url +'blog/entry/vote', {
		method:"post", 
		onSuccess: function(transport){						
			var res = transport.responseXML;
			var status = getXMLNodeValue(res, 'status');
			if (status == 3) {// vote once error
				var msg = new Message($('message_voteonce').innerHTML, 5500);
				md.addMessage(msg);
				window.setTimeout("Effect.Fade(loading);", 1000);
			} else if (status == 2) { // not login error
				var msg = new Message($('message_notlogin').innerHTML, -1);
				md.addMessage(msg);
				msg.onHide = function() {Effect.Fade(loading);};
				rating = type;
			} else if (status == 0) {
				var ratebar = getXMLNodeValue(res, 'ratebar');
				$('middle_bar').innerHTML = ratebar;
				var msg = new Message($('message_thankforvote').innerHTML, 2000);
				md.addMessage(msg);
				Effect.Fade(loading);
			}
		}, onFailure: function(transport){
		}, parameters:'entry_id='+entry_id+'&type='+type
	});
}

function favorite() {
	Effect.Appear(loading);
	new Ajax.Request(base_url +'blog/entry/favorite', {
		method:"post", 
		onSuccess: function(transport){						
			var res = transport.responseXML;
			var status = getXMLNodeValue(res, 'status');
			if (status == 3) {// vote once error
				var msg = new Message($('message_favorited').innerHTML, 3500);
				md.addMessage(msg);
				window.setTimeout("Effect.Fade(loading);", 1000);
			} else if (status == 2) { // not login error
				var msg = new Message($('message_notlogin').innerHTML, -1);
				md.addMessage(msg);
				msg.onHide = function() {Effect.Fade(loading);};
				fav = true;
			} else if (status == 0) {
				var ratebar = getXMLNodeValue(res, 'ratebar');
				$('middle_bar').innerHTML = ratebar;
				var msg = new Message($('message_thankforfavorite').innerHTML, 2000);
				md.addMessage(msg);
				Effect.Fade(loading);
			}
		}, onFailure: function(transport){
		}, parameters:'entry_id='+entry_id
	});
}

function thumbup() {dorate(1);}	
function thumbdown() {dorate(2);}
function show_cache() {$('blog_page').src = base_url+"blog/get_cached_entry/"+entry_id;}
/**********DISCUSSION WINDOW**************/
var firstTimeShowDiscuss = true;
var discussTab;
var metaInfo;
var commentEditor = false;
var commentScriptInserted = false;
var reply_id = '';
var needRefresh = false;
function discuss() {
	showDiscussion();
	if (pd.numShowing > 0) return;
	var msg = new Message($('comments_window'), -1, {action:'cut', copyback:true}, 'element');
	msg.onShow = function() {
		if (firstTimeShowDiscuss) { 
			loadToElement(base_url+'blog/discussion/ajax_load/'+entry_id+'/1/7', null, pd.getCurrentContentId(), null, false, {
				onSuccess:discuss_createTab
			});
		}
		firstTimeShowDiscuss = false;
	}
	pd.addMessage(msg);
}
function discuss_createTab() {
	if (discussTab) delete discussTab;
	if (metaInfo) delete metaInfo;
	editorCreated = false;
	discussTab = new Tab('tab_header', 'tab_body');
	metaInfo = new ContentSlider('tab_meta', {show:0});
	discussTab.onTabDisplay = tabDisplayHandle;
	discussTab.onTabChange = function(oldTab, newTab) {
		metaInfo.moveTo(newTab.tabIndex);
		if (newTab.tabId != 'tab_post') reply_id = '';
	}
	discussTab.start({defaultIndex:0, loadingElementID:'tab_loading_message'});
}
function tabDisplayHandle(tab_item) {
	checkTabSize(tab_item);
	if (tab_item.tabId == 'tab_post' && !commentEditor) {
		var successFunc = 
			function() {
			 	YAHOO.util.Event.onAvailable("comment_editor", 
			 		function() { 
				 		commentEditor = new YAHOO.widget.SimpleEditor('comment_editor', { 
						    height: '200px', 
						    width: '570px', 
						    dompath: true //Turns on the bar at the bottom 
						}); 
						$('ce_wrapper').className = "yui-skin-sam";
						commentEditor.render();
						commentEditor.invalidHTML = "script";
						discussTab.hideLoading();
					});
				commentScriptInserted = true;
		 	};
		if (!commentScriptInserted) {
			// use yui loader to load the script for editor
			discussTab.showLoading();
			var loader = new YAHOO.util.YUILoader(
			{
				require: ['simpleeditor'], 
				base: 'http://yui.yahooapis.com/2.6.0/build/',
				onSuccess: successFunc, 
				onFailure: function(o) {alert("error: " + YAHOO.lang.dump(o));} 
		    });
			loader.insert();
		} else {successFunc();}
	} else if (tab_item.tabId == 'tab_discussion') {
		if (needRefresh) {loadComments(1);needRefresh = false;}
	}
}
function checkTabSize(tab_item) {
	var e = $('tab_body');
	var h = e.getHeight();
	if (h > 300 && tab_item.tabId == 'tab_discussion') e.style.height = "300px";
	else e.style.height = 'auto';
}
function loadComments(page) {	// this function is very hacky
	var iframe = document.createElement("iframe");
	$("comments_window").appendChild(iframe);
	var idoc;
	if(iframe.contentDocument) idoc = iframe.contentDocument; // Firefox, Opera  
	else if(iframe.contentWindow)  idoc = iframe.contentWindow.document;// Internet Explorer  
	else if(iframe.document)  idoc = iframe.document;// Others?  
	idoc.open();idoc.close();
	var div = idoc.createElement("div");
	div.id = "theDIV";
	idoc.body.appendChild(div);
	discussTab.showLoading();
	loadToElement(base_url+'blog/discussion/ajax_load/'+entry_id+'/'+page+'/7', null, null, null, false, {
		onSuccess:function(transport) {
			div.innerHTML = transport.responseText;
			var cl = idoc.getElementById("tab_content_discussion").innerHTML;
			$("tab_content_discussion").innerHTML = cl;
			var meta = idoc.getElementById("tab_discussion_meta").innerHTML;
			$("tab_discussion_meta").innerHTML = meta;
			$("comments_window").removeChild(iframe);
			discussTab.hideLoading();
		}
	});
}
function showCommentPosting() {discussTab.moveTo('tab_post');}
function showDiscussion() { if (pd.numShowing > 0) Effect.Appear($(pd.getCurrentContentId()));  }
function hideDiscussion() { Effect.SwitchOff($(pd.getCurrentContentId())); }
function replyComment(val) {reply_id = val;showCommentPosting();}
function postComment() {
	var comment = commentEditor.getEditorHTML();
	comment = commentEditor.cleanHTML(comment);
	discussTab.showLoading();
	new Ajax.Request(base_url +'blog/discussion/save', {
		method:"post", 
		onSuccess: function(transport){
			var res = transport.responseXML;
			var msg = getXMLNodeValue(res, 'message');
			$('post_message').innerHTML = msg;
			discussTab.hideLoading();refreshCaptcha("captimg", "dcapt");
			var status = getXMLNodeValue(res, 'status');
			if (status == 0) needRefresh = true;
		},
		onFailure: function(transport){},
		parameters:$('discussionPost').serialize()+"&entry_id="+entry_id+"&comment="
					+encodeURIComponent(comment)+((reply_id != '')?("&reply_id="+escape(reply_id)):'')
	}); 
}
/****************************/
function search(form) {
	var keyword = $("searchbox").value;
	if (keyword == '' || keyword.length == 0) return;
	keyword = encodeURIComponent(keyword);
	var gsquery = 'http://www.google.com.sg/search?q=site%3Amottramdo.com+'+keyword+'&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a';
	window.location=gsquery;
	return false;
}
function ajax_login(button) {
	var form = button.up();
	while (form && !(form.nodeName.toUpperCase() == 'FORM')) {
		form = Element.up(form);
	}
	if (!form) {return;}
	
	button.previous().className = '';
	button.className = 'nodisplay';
	new Ajax.Request(base_url +'user/access/ajax_dologin', {
		method:"post", 
		onSuccess: function(transport){						
			var res = transport.responseXML;
			var status = getXMLNodeValue(res, 'status');
			if (status == 0) {
				md.hideMessage();
				var msg = new Message($('successful_login').innerHTML, 10000);
				md.addMessage(msg);
				if (rating != false) dorate(rating);
				if (fav != false) favorite();
				rating = false;
				fav = false;
			} else {
				var message = getXMLNodeValue(res, 'message');
				button.up().previous().innerHTML = message;
				button.previous().className = 'nodisplay';
				button.className = 'frmbttn'; 
			}			
		}, onFailure: function(transport){
		}, parameters:form.serialize(false)
	});
}

function checkIframeHeight() {
	var viewport = document.viewport.getDimensions();
	if (viewport.height-box_bottom_height != iframe.getHeight()) {
		iframe.style.height = (viewport.height-61)+"px";
	}
}

function refreshCaptcha(captchaContainer, value) {
	new Ajax.Request(base_url +'captchamaker/make/'+value, {
		method:"post",
		onSuccess:function(transport) {
			$(captchaContainer).innerHTML = transport.responseText;
		},
		onFailure:function(transport) {
		}
	});
}

function uv(value,str) {
	new Ajax.Request(base_url +'blog/uv/' + value+'/'+str, {
		method:"post"
	});							
}

/*****************************************************/
function disagree(){
		$('blog_page').src = "";
		$('finalnote').show();
		showBlocker();
	}
	
function agree(){
	$('disclaimer').hide();
}

function showBlocker() {
		$('blocker').style.display = 'block';
		if (window.innerWidth) {
			$('blocker').style.width = window.innerWidth+"px";
			$('blocker').style.height = window.innerHeight+"px";
		} else if (document.documentElement.clientWidth) {
			$('blocker').style.width = document.documentElement.clientWidth+"px";
			$('blocker').style.height = document.documentElement.clientHeight+"px";
		}
	}

function hideBlocker() {
	$('blocker').style.display = 'none';
}